#include "ClockModel.h"

ClockModel::ClockModel(QObject *parent)
    : QObject(parent)
    , m_timer(new QTimer(this))
    , m_is24HourFormat(true)
{
    // 初始化时间
    updateTime();
    
    // 连接定时器信号到更新槽
    connect(m_timer, &QTimer::timeout, this, &ClockModel::updateTime);
    
    // 启动定时器，每1000毫秒（1秒）触发一次
    m_timer->start(1000);
}

ClockModel::~ClockModel()
{
    if (m_timer->isActive()) {
        m_timer->stop();
    }
}

void ClockModel::setIs24HourFormat(bool format)
{
    if (m_is24HourFormat != format) {
        m_is24HourFormat = format;
        formatTime();  // 重新格式化时间
        emit formatChanged();
    }
}

void ClockModel::toggleTimeFormat()
{
    setIs24HourFormat(!m_is24HourFormat);
}

void ClockModel::startClock()
{
    if (!m_timer->isActive()) {
        m_timer->start(1000);
        updateTime();
    }
}

void ClockModel::stopClock()
{
    if (m_timer->isActive()) {
        m_timer->stop();
    }
}

void ClockModel::updateTime()
{
    // 获取当前日期时间
    m_dateTime = QDateTime::currentDateTime();
    
    // 格式化各个部分
    formatTime();
    formatDate();
    formatWeekDay();
}

void ClockModel::formatTime()
{
    QString newTime;
    
    if (m_is24HourFormat) {
        // 24小时制格式：HH:mm:ss
        newTime = m_dateTime.toString("HH:mm:ss");
    } else {
        // 12小时制格式：h:mm:ss AP (AM/PM)
        newTime = m_dateTime.toString("h:mm:ss AP");
    }
    
    if (m_currentTime != newTime) {
        m_currentTime = newTime;
        emit timeChanged();
    }
}

void ClockModel::formatDate()
{
    // 日期格式：yyyy年MM月dd日
    QString newDate = m_dateTime.toString("yyyy年MM月dd日");
    
    if (m_currentDate != newDate) {
        m_currentDate = newDate;
        emit dateChanged();
    }
}

void ClockModel::formatWeekDay()
{
    // 获取星期几 (1=Monday, 7=Sunday)
    int dayOfWeek = m_dateTime.date().dayOfWeek();
    
    // 中文星期数组
    static const QStringList weekDays = {
        "星期一", "星期二", "星期三", "星期四",
        "星期五", "星期六", "星期日"
    };
    
    QString newWeekDay = weekDays[dayOfWeek - 1];
    
    if (m_currentWeekDay != newWeekDay) {
        m_currentWeekDay = newWeekDay;
        emit weekDayChanged();
    }
}

